<template>
  <div style="margin: 20px">
    <el-input v-model="roleName" size="normal" clearable disabled></el-input>
    <el-tree
      ref="treeEl"
      style="margin: 20px 0"
      :data="initPermissAuth"
      :show-checkbox="true"
      node-key="id"
      default-expand-all
      :default-checked-keys="checkedAttr"
      :props="defaultProps"
    >
    </el-tree>
    <div>
      <el-button type="primary" size="default" @click="save">保存</el-button>
      <el-button size="default" @click="cancelSave" style="margin-left: 12px"
        >取消</el-button
      >
    </div>
  </div>
</template>

<script>
import { reqGetToAssignById,reqDoAssignAcl } from "@/api/auth/permission";
import useCheckedArr from "@/utils/useCheckedArr";
export default {
  name: "Auth",
  data() {
    return {
      roleName: "",
      permissionVo: {
        roleId: null, //当前角色对应id的初始值
        permissionIdList: [], //给角色分配权限组成的id数组
      },
      initPermissAuth: [], //权限列表初始化数据
      checkedAttr: [], //选中的权限id数组 初始值
      defaultProps: {
        // tree控件所展示的信息
        children: "children",
        label: "name",
      },
    };
  },
  methods: {
    //获取当前进入权限分配的角色相关信息
    getRoleInfo() {
      const { id, roleName } = this.$route.query;
      this.roleName = roleName;
      this.permissionVo.roleId = id;
    },
    //获取当前角色权限设置初始数据
    async getInitPermissAuth() {
      try {
        const result = await reqGetToAssignById(this.permissionVo.roleId);
        this.initPermissAuth = result.children;
        this.checkedAttr = useCheckedArr(result.children);
      } catch (error) {
        this.$message({
          message: error.message,
          type: "error",
        });
      }
    },
    //点击取消按钮事件回调
    cancelSave() {
      this.$router.push({
        name: "Role",
      });
    },
    //点击提交按钮事件回调函数
    async save() {
      const result = this.getIdArr();
      this.permissionVo.permissionIdList = result
      try {
        await reqDoAssignAcl(this.permissionVo)
        this.$message({
          message: '恭喜你，分配权限成功！',
          type: 'success'
        })
        this.cancelSave()
      } catch (error) {
        this.$message({
          message: error.message,
          type: 'error'
        })
      }
    },
    //获取当前已选中的Tree id列表
    getIdArr() {
      const attr1 = this.$refs.treeEl.getHalfCheckedKeys();
      const attr2 = this.$refs.treeEl.getCheckedKeys();
      return [...attr1, ...attr2];
    },
  },
  mounted() {
    this.getRoleInfo();
    this.getInitPermissAuth();
  },
};
</script>

<style lang="scss" scoped></style>
